package com.heima.wemedia.config;

import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import jdk.nashorn.internal.runtime.options.Options;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

import static com.heima.utils.common.WmThreadLocalUtil.WM_USER_THREAD_LOCAL;

@Slf4j
public class WebTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //解析token
        String token = request.getHeader("token");
        //取出token中的用户信息
        //Optional<String> token1 = Optional.ofNullable(token);
        if(!StringUtils.isEmpty(token)){
            Claims claims = AppJwtUtil.getClaimsBody(token);
            Integer id = (Integer) claims.get("id");
            WmUser wmUser = new WmUser();
            wmUser.setId(id);
            WM_USER_THREAD_LOCAL.set(wmUser);
            return true;
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("清理threadlocal...");
        WM_USER_THREAD_LOCAL.remove();
    }
}
